package com.wangdao.wechatmall.service.admin;

import com.github.pagehelper.PageHelper;
import com.wangdao.wechatmall.bean.bo.wx.WXCouponDTO;
import com.wangdao.wechatmall.bean.pojo.*;
import com.wangdao.wechatmall.bean.vo.wx.WXCartIndexVO;
import com.wangdao.wechatmall.bean.vo.wx.WXCouponSelectListVO;
import com.wangdao.wechatmall.bean.vo.wx.WXCouponVO;
import com.wangdao.wechatmall.mapper.CouponMapper;
import com.wangdao.wechatmall.mapper.CouponUserMapper;
import com.wangdao.wechatmall.mapper.UserMapper;
import com.wangdao.wechatmall.service.wx.WXCartService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * CouponServiceImpl
 * created by feng on 7/12/21
 */
@Service
public class CouponServiceImpl implements CouponService {

    @Autowired
    CouponMapper couponMapper;

    @Autowired
    CouponUserMapper couponUserMapper;

    @Autowired
    UserMapper userMapper;

    @Autowired
    WXCartService wXCartService;

    @Override
    public List<WXCouponVO> myList(Integer status, Integer page, Integer size) {

        // 更新优惠券status
        couponUserMapper.updateStatusByDate();

        // set PageHelper
        PageHelper.startPage(page, size);

        if (status == null && "".equals(status)) {
            CouponExample couponExample = new CouponExample();
            CouponExample.Criteria criteria = couponExample.createCriteria();

            // 去掉已下架的优惠券
            criteria.andTypeNotEqualTo(Short.parseShort("3"));

            // status 相同
            criteria.andStatusEqualTo(Short.parseShort(status.toString()));

            List<Coupon> coupons = couponMapper.selectByExample(couponExample);

            List<WXCouponVO> wxCouponVOList = new ArrayList<WXCouponVO>();

            Iterator<Coupon> iterator = coupons.iterator();
            while (iterator.hasNext()) {
                Coupon coupon = iterator.next();

                WXCouponVO wxCouponVO = new WXCouponVO();
                wxCouponVO.setDesc(coupon.getDesc());
                wxCouponVO.setEndTime(coupon.getEndTime().toString());
                wxCouponVO.setId(coupon.getId());
                wxCouponVO.setDiscount(coupon.getDiscount().toString());
                wxCouponVO.setStartTime(coupon.getStartTime().toString());
                wxCouponVO.setMin(coupon.getMin().toString());
                wxCouponVO.setName(coupon.getName());
                wxCouponVO.setTag(coupon.getTag());

                wxCouponVOList.add(wxCouponVO);
            }
            return wxCouponVOList;
        }

        // 获取userId
        String userName = (String) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        int userId = userMapper.queryId(userName);
        List<WXCouponVO> wxCouponVOList = couponMapper.selectCouponDetailByUserID(userId, status);


        return wxCouponVOList;
    }

    @Override
    public Integer exchange(String code) {

        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();

        // 1. 判断是否有这个券
        // code 是否相等
        criteria.andCodeEqualTo(code);
        // 是可兑换的券
        criteria.andTypeEqualTo(Short.parseShort("2"));
        // 未删除
        criteria.andDeletedEqualTo(false);
        // 是否是正常可用
        criteria.andStatusEqualTo(Short.parseShort("0"));

        List<Coupon> coupons = couponMapper.selectByExample(couponExample);

        // 2.1 如果没有符合条件的券， 返回404
        if (coupons.size() == 0) {
            return 404;
        }

        // 2.2 有符合条件的券,  判断该用户是否有这个券了
        CouponUserExample couponUserExample = new CouponUserExample();
        CouponUserExample.Criteria criteria1 = couponUserExample.createCriteria();
        String userName = (String) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        int userId = userMapper.queryId(userName);

        // userId 相同
        criteria1.andUserIdEqualTo(userId);

        // couponId 相同
        int couponId = -1;
        Iterator<Coupon> iterator1 = coupons.iterator();
        while (iterator1.hasNext()) {
            Coupon next = iterator1.next();
            couponId = next.getId();
        }
        criteria1.andCouponIdEqualTo(couponId);

        // 查找couponUser中是否有相同的券
        List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

        if (couponUsers.size() > 0) {
            // 已有此券
            return 0;
        }


        // 3. 没有券的情况，updateCoupon total
        Iterator<Coupon> iterator = coupons.iterator();
        Coupon next = iterator.next();

        // 3.1 如果total为0, 代表的是无限的
        Coupon coupon = new Coupon();

        if (next.getTotal() == 0) {
            coupon.setTotal(0);
        } else {
            // 3.2 如果total不为0, 代表是有限的
            coupon.setTotal(next.getTotal() - 1);
            // 3.2.1 如果删除后， next.getTotal() - 1  等于 0, 则券失效，下架该券
            if ((next.getTotal() - 1) == 0) {
                coupon.setStatus(Short.parseShort("2"));
            }
        }
        coupon.setId(next.getId());
        couponMapper.updateByPrimaryKeySelective(coupon);

        // 4. 插入优惠券至coupUser中
        CouponUser couponUser = new CouponUser();
        Date date = new Date();
        // 4.1 获取userId
        couponUser.setUserId(userId);
        couponUser.setCouponId(coupon.getId());
        couponUser.setStatus(coupon.getStatus());

        // 插入优惠券
        // 根据time_type进行判断0是有效天数， 1 是优惠券有效期
        if (next.getTimeType() == 0) {
            couponUser.setStartTime(date);

            // 时间相加, 设置endTime
            GregorianCalendar calendar = new GregorianCalendar();
            calendar.setTime(date);
            calendar.add(calendar.DATE, next.getDays());

            // 设置endDate
            Date endDate = new Date();
            endDate = calendar.getTime();
            couponUser.setEndTime(endDate);

        } else {
            // time_type 是1时,是优惠券的有效期
            couponUser.setStartTime(next.getStartTime());
            couponUser.setEndTime(next.getEndTime());
        }

        couponUser.setUpdateTime(date);
        couponUser.setAddTime(date);
        couponUser.setDeleted(false);
        couponUser.setStatus(Short.parseShort("0"));

        // insert CouponUser
        int affectedRow = couponUserMapper.insert(couponUser);

        return affectedRow;
    }

    @Override
    public Integer receive(String couponId) {

        int affectedRow = -1;

        // 1. 获取当前的用户id
        Subject subject = SecurityUtils.getSubject();
        if (subject.getPrincipals() != null && subject.getPrincipals().getPrimaryPrincipal() != null) {
            String username = (String) subject.getPrincipals().getPrimaryPrincipal();

            int userID = userMapper.queryId(username);

            //find coupon detail by couponId
            Coupon coupon = couponMapper.selectByPrimaryKey(Integer.parseInt(couponId));

            //判断是否只能领一张
            if (coupon.getLimit() == 1) {
                // 查找userCoupon中是否有这张优惠券
                CouponUserExample couponUserExample = new CouponUserExample();
                CouponUserExample.Criteria criteria = couponUserExample.createCriteria();

                // 当前用户已有这张券
                criteria.andUserIdEqualTo(userID);
                criteria.andCouponIdEqualTo(coupon.getId());

                List<CouponUser> couponUsers = couponUserMapper.selectByExample(couponUserExample);

                // 该券已经获得
                if (couponUsers.size() == 1) {
                    return 0;
                }
            }


            // insert coupon to coupon user
            CouponUser couponUser = new CouponUser();

            Date date = new Date();
            couponUser.setCouponId(coupon.getId());
            couponUser.setUserId(userID);
            couponUser.setStatus(Short.parseShort("0"));

            // 根据time_type进行判断0是有效天数， 1 是优惠券有效期
            if (coupon.getTimeType() == 0) {
                couponUser.setStartTime(date);

                // 时间相加, 设置endTime
                GregorianCalendar calendar = new GregorianCalendar();
                calendar.setTime(date);
                calendar.add(calendar.DATE, coupon.getDays());

                // 设置endDate
                Date endDate = new Date();
                endDate = calendar.getTime();
                couponUser.setEndTime(endDate);
            }

            // time_type 是1时,是优惠券的有效期
            couponUser.setStartTime(coupon.getStartTime());
            couponUser.setEndTime(coupon.getEndTime());
            couponUser.setUpdateTime(date);
            couponUser.setAddTime(date);
            couponUser.setDeleted(false);
            couponUser.setStatus(Short.parseShort("0"));

            // insert CouponUser
            affectedRow = couponUserMapper.insert(couponUser);
        }

        return affectedRow;
    }

    @Override
    public List<WXCouponDTO> list(Integer page, Integer size) {
        PageHelper.startPage(page, size);

        // 1. 更新已过期的优惠券, 将deleted改为1, status改为1
        couponMapper.updateStatusByDate();


        // 2. 构造查找条件
        CouponExample couponExample = new CouponExample();
        CouponExample.Criteria criteria = couponExample.createCriteria();
        // 去掉已经删除的优惠券
        criteria.andDeletedEqualTo(false);
        // 去掉余量为0的-> 用status 为 2 代表优惠券已发完, 下架
        criteria.andStatusNotEqualTo(Short.parseShort("2"));
        // 去掉优惠券已过期的
        criteria.andStatusNotEqualTo(Short.parseShort("1"));
        // 去掉用兑换码的 Type 为2的
        criteria.andTypeNotEqualTo(Short.parseShort("2"));


        // construct List<WXCouponDTO>
        ArrayList<WXCouponDTO> wxCouponList = new ArrayList<>();

        // 格式化date
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 时间相加
        GregorianCalendar calendar = new GregorianCalendar();
        List<Coupon> couponsList = couponMapper.selectByExample(couponExample);
        Iterator<Coupon> iterator = couponsList.iterator();
        while (iterator.hasNext()) {
            Coupon coupon = iterator.next();
            WXCouponDTO wxCouponDTO = new WXCouponDTO();

            // 获取默认值
            Date startDate = new Date();
            Date endDate = coupon.getEndTime();

            // if time_type = 0， 代表l领取时间的有效天数
            if (coupon.getTimeType() == Short.parseShort("0")) {
                calendar.setTime(startDate);

                calendar.add(calendar.DATE, coupon.getDays());
                endDate = calendar.getTime();
            }


            wxCouponDTO.setDesc(coupon.getDesc());
            wxCouponDTO.setDiscount(coupon.getDiscount().intValue());
            wxCouponDTO.setEndTime(simpleDateFormat.format(endDate.getTime()));
            wxCouponDTO.setId(coupon.getId());
            wxCouponDTO.setName(coupon.getName());
            wxCouponDTO.setMin(coupon.getMin().intValue());
            wxCouponDTO.setStartTime(simpleDateFormat.format(startDate.getTime()));
            wxCouponDTO.setTag(coupon.getTag());
            wxCouponDTO.setDays(Integer.parseInt(coupon.getDays().toString()));

            // add wxCouponDTO to wxCouponList
            wxCouponList.add(wxCouponDTO);
        }
        return wxCouponList;
    }

    @Override
    public List<WXCouponSelectListVO> selectList(Integer cartId, Integer grouponRulesId) {
        // 获取userId
        String userName = (String) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        int userID = userMapper.queryId(userName);

        List<WXCouponSelectListVO> wxCouponSelectListVOList = couponUserMapper.selectListByUserID(userID);

        return wxCouponSelectListVOList;
    }
}